package com.topisv.tms.web.edi;

import java.io.PrintWriter;
import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.topisv.tms.entity.AreaGroup;
import com.topisv.tms.entity.EdiOrder;
import com.topisv.tms.entity.EdiOrderItem;
import com.topisv.tms.service.AreaGroupService;
import com.topisv.tms.service.EdiOrderItemService;
import com.topisv.tms.service.EdiOrderService;
import com.topisv.tms.utils.TimeUtil;
import com.topisv.tms.utils.date.TopIsvDateUtils;
import com.topisv.tms.web.dto.ChartDTO;

import net.sf.json.JSONObject;

@Controller
@RequestMapping(value = "/soce")
public class ChartController {
    
    private static final Logger logger = LoggerFactory.getLogger(ChartController.class);
    
	
	private static int pagzSize=10000;
	@Autowired
	private EdiOrderService ediOrderService;
	@Autowired
	private EdiOrderItemService ediOrderItemService;
	@Autowired
	private AreaGroupService areaGroupService;

	
	/**
	 * 获得下一个月
	 * @param crtime
	 * @return
	 * @throws ParseException
	 */
	private Date getYesterDay(String crtime,int index) throws ParseException{
		String temp=crtime.substring(5, 7);
		int mouthNumber=0;
		if(temp.startsWith("0")){
			mouthNumber=Integer.parseInt(temp.substring(1));
		}else{
			mouthNumber=Integer.parseInt(temp);
		}
		crtime=crtime.substring(0, 5)+(mouthNumber+index)+crtime.substring(7);
		return TimeUtil.getDate(crtime);
	}

	@RequestMapping(value = "ajaxChart",method=RequestMethod.GET)
	public void ajaxChart(@RequestParam(value="status") int status, 
			@RequestParam(value="time") String time, 
			@RequestParam(value="jsonpcallback") String callback, 
			HttpServletResponse response) {
		Map<String, Object> searchParams = null;
		List<EdiOrder> ediOrderAllLists = null;//总的订单数
		Date nowDate = null;//当前时间
		Date firstDate = null;//起始时间
		Date endDate = null;//终止时间
		Date yesterDay = null;//比当前时间小一个单位的时间
		String crtime = null;
		
		int zero = 0;
		int one = 0;
		int two = 0;
		int three = 0;
		int four = 0;
		int five = 0;
		int six = 0;
		int seven = 0;
		int eigth = 0;
		int nine = 0;
		int ten = 0;
		int eleven = 0;
		int twelve = 0;
		int thirteen = 0;
		int fourteen = 0;
		int fifteen = 0;
		int sixteen = 0;
		int seventeen = 0;
		int eighteen = 0;
		int nineteen = 0;
		int twenty = 0;
		int twentyOne = 0;
		int twentyTwo = 0;
		int twentyThree = 0;
		int twentyFour = 0;
		int twentyFive = 0;
		int twentySix = 0;
		int twentySeven = 0;
		int twentyEigth = 0;
		int twentyNine = 0;
		int thirty=0;
		
		int ediOrderSingleLists=0;//单件
		int ediOrderMultipleLists=0;//多件
		
		Map<String, Integer> areaGroupsSets =null;//保存服务网点的信息
		Map<String, Integer> proviceSets=null;//保存省份信息
		Page<EdiOrder> ediOrdersPages =null;
		List<AreaGroup> areaGroups = null;
		
		JSONObject json=null;
		PrintWriter out=null;
		ChartDTO chartDTO=null;
		try {
			//response.setContentType("application/json;charset=UTF-8"); //这里的格式是json
			//response.setHeader("Cache-Control","no-cache");
			json=new JSONObject();
			out=response.getWriter();
			chartDTO=new ChartDTO();
			areaGroupsSets = new HashMap<String, Integer>();
			proviceSets = new HashMap<String, Integer>();
			areaGroups = areaGroupService.findAll();
			searchParams = new HashMap<String, Object>();
			nowDate = new Date();
			crtime = TimeUtil.getNowDateString(nowDate);// 格式化时间格式yyyy-MM-dd HH:mm:ss
			
			if(status==1){//天为单位
				nowDate = TimeUtil.getDate(crtime);// 格式化时间格式yyyy-MM-dd
				yesterDay = TopIsvDateUtils.addDays(nowDate, -1);//减少一天
				yesterDay = TopIsvDateUtils.addHours(yesterDay, -14);// 延后14个小时
				chartDTO.setDay("active");
			}else if(status==2){//月为单位
				crtime=crtime.substring(0, 8)+"01"+crtime.substring(10);
				nowDate = TimeUtil.getDate(crtime);// 格式化时间格式yyyy-MM-dd
				yesterDay = getYesterDay(crtime,-1);//减少一个月
				yesterDay = TopIsvDateUtils.addHours(yesterDay, -14);// 延后14个小时
				chartDTO.setMouth("active");
			}
			chartDTO.setYesterDay( yesterDay.toString());
			nowDate = TopIsvDateUtils.addHours(nowDate, -14);// 延后14个小时
			if ("0".equals(time)) {
				if(status==1){
					searchParams.put("GTE_crtime", nowDate.toString());
				}else if(status==2){
					crtime=crtime.substring(0, 8)+"01"+crtime.substring(10);
					nowDate = TimeUtil.getDate(crtime);// 格式化时间格式yyyy-MM-dd
					searchParams.put("GTE_crtime", nowDate.toString());
				}
			} else {
				String timeTemp = time;
				if (timeTemp.indexOf("-") > 0) {
					if(status==1){
						firstDate = TimeUtil.getDate(timeTemp);
						firstDate = TopIsvDateUtils.addHours(firstDate, -14);// 延后14个小时
						searchParams.put("GTE_crtime", firstDate.toString());
						firstDate = new Date((String) searchParams.get("GTE_crtime"));
						endDate = TopIsvDateUtils.addDays(firstDate, 1);
						endDate = TopIsvDateUtils.addHours(endDate, -14);// 延后14个小时
						searchParams.put("LT_adtime", endDate.toString());
					}else if(status==2){
						firstDate = TimeUtil.getDate(timeTemp);
						crtime = TimeUtil.getNowDateString(firstDate);// 格式化时间格式yyyy-MM-dd HH:mm:ss
						crtime=crtime.substring(0, 8)+"01"+crtime.substring(10);
						firstDate = TimeUtil.getDate(crtime);// 格式化时间格式yyyy-MM-dd
						endDate = TopIsvDateUtils.addMonths(firstDate, 1);//增加一个月
						firstDate = TopIsvDateUtils.addHours(firstDate, -14);// 延后14个小时
						endDate = TopIsvDateUtils.addHours(endDate, -14);// 延后14个小时
						searchParams.put("GTE_crtime", firstDate.toString());
						searchParams.put("LT_adtime", endDate.toString());
					}
					
				
				} else {
					firstDate= new Date(
							(String) searchParams.get("GTE_crtime"));
					if(status==1){
						endDate = TopIsvDateUtils.addDays(firstDate, 1);//增加一天
						endDate = TopIsvDateUtils.addHours(endDate, -14);// 延后14个小时
						searchParams.put("LT_adtime", endDate.toString());
					}else if(status==2){
						endDate = TopIsvDateUtils.addMonths(firstDate, 1);//增加一个月
						endDate = TopIsvDateUtils.addHours(endDate, -14);// 延后14个小时
						searchParams.put("LT_adtime", endDate.toString());
					}
				
				}
			}
			ediOrdersPages =ediOrderService.crTimeLists(searchParams, 1, pagzSize);
			int totalPages=ediOrdersPages.getTotalPages();
			ediOrderAllLists=ediOrdersPages.getContent();
			int i=1;
			while(i<=totalPages){
				i++;
				for (EdiOrder ediOrderAllList : ediOrderAllLists) {
					String orderType = ediOrderAllList.getOrderType();
					Date date = ediOrderAllList.getCrtime();
					String provna = ediOrderAllList.getProvna();//省名称
					String provco=ediOrderAllList.getProvco();//省编码
					String crtimeTemp = date.toString();
					
					//统计单件与多件
					if ("single".equals(orderType)) {
						ediOrderSingleLists++;
					} else if ("multiple".equals(orderType)) {
						ediOrderMultipleLists++;
					} else {
						List<EdiOrderItem> tempEdiOrderItems = ediOrderItemService.findByCustomerCodeAndOrdeno(ediOrderAllList.getCustomerCode(), ediOrderAllList.getOrdeno());
						if (tempEdiOrderItems.size() > 1) {
							ediOrderMultipleLists++;
							ediOrderAllList.setOrderType("multiple");
						} else {
							EdiOrderItem tempEdiOrderItem = tempEdiOrderItems.get(0);
							if (tempEdiOrderItem.getQty() > 1) {
								ediOrderMultipleLists++;
								ediOrderAllList.setOrderType("multiple");
							} else {
								ediOrderSingleLists++;
								ediOrderAllList.setOrderType("single");
							}
						}
						ediOrderService.save(ediOrderAllList);
					}		
					//统计日与月
					if(status==1){
						String temp = crtimeTemp.substring(11, 13);
						if (temp.equals("00")) {
							zero++;
						} else if (temp.equals("01")) {
							one++;
						} else if (temp.equals("02")) {
							two++;
						} else if (temp.equals("03")) {
							three++;
						} else if (temp.equals("04")) {
							four++;
						} else if (temp.equals("05")) {
							five++;
						} else if (temp.equals("06")) {
							six++;
						} else if (temp.equals("07")) {
							seven++;
						} else if (temp.equals("08")) {
							eigth++;
						} else if (temp.equals("09")) {
							nine++;
						} else if (temp.equals("10")) {
							ten++;
						} else if (temp.equals("11")) {
							eleven++;
						} else if (temp.equals("12")) {
							twelve++;
						} else if (temp.equals("13")) {
							thirteen++;
						} else if (temp.equals("14")) {
							fourteen++;
						} else if (temp.equals("15")) {
							fifteen++;
						} else if (temp.equals("16")) {
							sixteen++;
						} else if (temp.equals("17")) {
							seventeen++;
						} else if (temp.equals("18")) {
							eighteen++;
						} else if (temp.equals("19")) {
							nineteen++;
						} else if (temp.equals("20")) {
							twenty++;
						} else if (temp.equals("21")) {
							twentyOne++;
						} else if (temp.equals("22")) {
							twentyTwo++;
						} else if (temp.equals("23")) {
							twentyThree++;
						}
					}else if(status==2){
						String temp = crtimeTemp.substring(8, 10);
						if (temp.equals("01")) {
							zero++;
						} else if (temp.equals("02")) {
							one++;
						} else if (temp.equals("03")) {
							two++;
						} else if (temp.equals("04")) {
							three++;
						} else if (temp.equals("05")) {
							four++;
						} else if (temp.equals("06")) {
							five++;
						} else if (temp.equals("07")) {
							six++;
						} else if (temp.equals("08")) {
							seven++;
						} else if (temp.equals("09")) {
							eigth++;
						} else if (temp.equals("10")) {
							nine++;
						} else if (temp.equals("11")) {
							ten++;
						} else if (temp.equals("12")) {
							eleven++;
						} else if (temp.equals("13")) {
							twelve++;
						} else if (temp.equals("14")) {
							thirteen++;
						} else if (temp.equals("15")) {
							fourteen++;
						} else if (temp.equals("16")) {
							fifteen++;
						} else if (temp.equals("17")) {
							sixteen++;
						} else if (temp.equals("18")) {
							seventeen++;
						} else if (temp.equals("19")) {
							eighteen++;
						} else if (temp.equals("20")) {
							nineteen++;
						} else if (temp.equals("21")) {
							twenty++;
						} else if (temp.equals("22")) {
							twentyOne++;
						} else if (temp.equals("23")) {
							twentyTwo++;
						} else if (temp.equals("24")) {
							twentyThree++;
						}else if (temp.equals("25")) {
							twentyFour++;
						} else if (temp.equals("26")) {
							twentyFive++;
						}else if (temp.equals("27")) {
							twentySix++;
						} else if (temp.equals("28")) {
							twentySeven++;
						}else if (temp.equals("29")) {
							twentyEigth++;
						} else if (temp.equals("30")) {
							twentyNine++;
						}else if (temp.equals("31")) {
							thirty++;
						}
					}
					
					//统计省份
					if(provna!=null){
						if (proviceSets.get(provna) == null) {
							proviceSets.put(provna, 1);
						} else {
							proviceSets.put(provna, proviceSets.get(provna) + 1);
						}
					}
					
					//统计网点
					for (AreaGroup areaGroup : areaGroups) {
						String areas = areaGroup.getAreas();
						if (areas == null) {
							continue;
						}
						String areaGroupName = areaGroup.getGroupName();
						String[] tempAreas = areas.split(";");
						if (isProvco(provco, tempAreas)) {
							if (areaGroupsSets.get(areaGroupName+":"+provna) == null) {
								areaGroupsSets.put(areaGroupName+":"+provna, 1);
							} else {
								areaGroupsSets.put(areaGroupName+":"+provna,
										1 + areaGroupsSets.get(areaGroupName+":"+provna));
							}
							break;
						}
					}
					
				}
				if(i<=totalPages){
					ediOrdersPages =ediOrderService.crTimeLists(searchParams, i, pagzSize);
					ediOrderAllLists=ediOrdersPages.getContent();
				}
				
			}
			setAreaGroupProvice(areaGroupsSets,chartDTO);
			setArea(proviceSets,chartDTO);
			chartDTO.setEdiOrderAllLists((ediOrderSingleLists+ediOrderMultipleLists));//("ediOrderAllLists", (ediOrderSingleLists+ediOrderMultipleLists));
			chartDTO.setEdiOrderSingleLists(ediOrderSingleLists);//("ediOrderSingleLists", ediOrderSingleLists);
			chartDTO.setEdiOrderMultipleLists(ediOrderMultipleLists);//("ediOrderMultipleLists", ediOrderMultipleLists);
			chartDTO.setZero(zero);//("zero", zero);
			chartDTO.setOne(one);//("one", one);
			chartDTO.setTwo(two);//("two", two);
			chartDTO.setThree(three);//("three", three);
			chartDTO.setFour(four);//("four", four);
			chartDTO.setFive(five);//("five", five);
			chartDTO.setSix(six);//("six", six);
			chartDTO.setSeven(seven);//("seven", seven);
			chartDTO.setEigth(eigth);//("eigth", eigth);
			chartDTO.setNine(nine);//("nine", nine);
			chartDTO.setTen(ten);//("ten", ten);
			chartDTO.setEleven(eleven);//("eleven", eleven);
			chartDTO.setTwelve(twelve);//("twelve", twelve);
			chartDTO.setThirteen(thirteen);//("thirteen", thirteen);
			chartDTO.setFourteen(fourteen);//("fourteen", fourteen);
			chartDTO.setFifteen(fifteen);//("fifteen", fifteen);
			chartDTO.setSixteen(sixteen);//("sixteen", sixteen);
			chartDTO.setSeventeen(seventeen);//("seventeen", seventeen);
			chartDTO.setNineteen(nineteen);//("nineteen", nineteen);
			chartDTO.setEighteen(eighteen);//("eighteen", eighteen);
			chartDTO.setTwenty(twenty);//("twenty", twenty);
			chartDTO.setTwentyOne(twentyOne);//("twentyOne", twentyOne);
			chartDTO.setTwentyTwo(twentyTwo);//("twentyTwo", twentyTwo);
			chartDTO.setTwentyThree(twentyThree);//("twentyThree", twentyThree);
			chartDTO.setTwentyFour(twentyFour);//("twentyFour", twentyFour);
			chartDTO.setTwentyFive(twentyFive);//("twentyFive", twentyFive);
			chartDTO.setTwentySix(twentySix);//("twentySix", twentySix);
			chartDTO.setTwentySeven(twentySeven);//("twentySeven", twentySeven);
			chartDTO.setTwentyEigth(twentyEigth);//("twentyEigth", twentyEigth);
			chartDTO.setTwentyNine(twentyNine);//("twentyNine", twentyNine);
			chartDTO.setThirty(thirty);//("thirty", thirty);
			json.put("status", "1");
			json.put("content", chartDTO);
			out.print(callback+"("+json.toString()+")");
		
		} catch (Exception e) {
			json.put("status", "0");
			json.put("content", e.getMessage());
			out.print(json.toString());
			
			logger.error("error",e);
		}
		logger.info(json.toString());
	}

	private void setAreaGroupProvice(Map<String, Integer> areaGroupsSets, ChartDTO model){
		StringBuffer areaGroupString = new StringBuffer();//显示名称
		StringBuffer areaGroupNumber = new StringBuffer();//显示数字(绘图专用)
		StringBuffer areaGroupProvice=new StringBuffer();
		Map<String, Integer> areaGroupsMaps=new HashMap<String, Integer>();//网点汇总
		for (String key : areaGroupsSets.keySet()) {
			String[] keys=key.split(":");
			if(areaGroupsMaps.get(keys[0])==null){
				areaGroupsMaps.put(keys[0], areaGroupsSets.get(key));
			}else{
				areaGroupsMaps.put(keys[0], areaGroupsSets.get(key)+areaGroupsMaps.get(keys[0]));
			}
			if("".equals(areaGroupProvice.toString())){
				areaGroupProvice.append(keys[0]+"："+keys[1]+"("+areaGroupsSets.get(key)+")&nbsp;&nbsp;<p>");
			}else{
				String temp=areaGroupProvice.toString();
				if(temp.contains(keys[0])){
					int fromIndex=temp.lastIndexOf(keys[0]);
					int endIndex=temp.indexOf("<p>", fromIndex);
					areaGroupProvice.insert(endIndex, keys[1]+"("+areaGroupsSets.get(key)+")&nbsp;&nbsp;");
				}else{
					areaGroupProvice.append(keys[0]+"："+keys[1]+"("+areaGroupsSets.get(key)+")&nbsp;&nbsp;<p>");
				}
			}
		}
		
		for (String key : areaGroupsMaps.keySet()) {
			if ("".equals(areaGroupString.toString())) {
				areaGroupString.append("[\"" + key + "("
						+ areaGroupsMaps.get(key) + ")\"");
			} else {
				areaGroupString.append(",\"" + key + "("
						+ areaGroupsMaps.get(key) + ")\"");
			}
			if ("".equals(areaGroupNumber.toString())) {
				areaGroupNumber.append("[" + areaGroupsMaps.get(key));
			} else {
				areaGroupNumber.append("," + areaGroupsMaps.get(key));
			}
		}

		areaGroupString.append("]");
		areaGroupNumber.append("]");
		model.setAreaGroupString(areaGroupString.toString());//("areaGroupString", areaGroupString.toString());
		model.setAreaGroupNumber(areaGroupNumber.toString());//("areaGroupNumber", areaGroupNumber.toString());
		model.setAreaGroupProvice(areaGroupProvice.toString());//("areaGroupProvice", areaGroupProvice.toString());
	}



	private boolean isProvco(String provco, String[] areas) {
		for (String area : areas) {
			if (provco.equals(area)) {
				return true;
			}
		}
		return false;
	}

	
	/**
	 * 设置网点
	 * 
	 * @param ediOrderAllLists
	 * @param model
	 */
	private void setArea( Map<String, Integer> proviceSets, ChartDTO model) {
		StringBuffer key = new StringBuffer();
		StringBuffer value = new StringBuffer();
		for (String tempKey : proviceSets.keySet()) {
			if ("".equals(key.toString())) {
				key.append("[\"" + tempKey + "(" + proviceSets.get(tempKey)
						+ ")\"");
			} else {
				key.append(",\"" + tempKey + "(" + proviceSets.get(tempKey)
						+ ")\"");
			}

			if ("".equals(value.toString())) {
				value.append("[" + proviceSets.get(tempKey));
			} else {
				value.append("," + proviceSets.get(tempKey));
			}
		}
		key.append("]");
		value.append("]");
		model.setKey(key.toString());//("key", key.toString());
		model.setValue(value.toString());//("value", value.toString());
	}
}
